package com.agrm.utils;


import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;

public class WebAppUtils {
    /**
     * 响应json数据
     *
     * @param resp 响应对象
     * @param json json
     */
    public static void writeJson(HttpServletResponse resp, String json) throws IOException {
        resp.setContentType("application/json;charset=utf-8");
        PrintWriter out = resp.getWriter();
        out.write(json);
        out.flush();
    }

    /**
     * 判断是否ajax请求
     *
     * @param request 请求对象
     * @return 是否ajax请求
     */
    public static boolean isAjaxRequest(HttpServletRequest request) {
        String requestType = request.getHeader("X-Requested-With");
        return "XMLHttpRequest".equals(requestType);
    }

    /**
     * 判断是否feign请求
     *
     * @param request 请求对象
     * @return 是否feign请求
     */
    public static boolean isFeignRequest(HttpServletRequest request) {
        String requestSource = request.getHeader("X-Request-Source");
        return "feign-client".equals(requestSource);
    }

    /**
     * 判断是否axios请求
     *
     * @param request 请求对象
     * @return 请求源
     */
    public static boolean isAxiosRequest(HttpServletRequest request) {
        return "axios".equals(request.getHeader("X-Request-Source"));
    }

    //获取客户端ip地址
    public static String getClientIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr(); //回退到直接连接IP
        }
        // 处理多IP情况（如：X-Forwarded-For: client, proxy1, proxy2）
        return ip.split(",")[0].trim();
    }
}